from django.http import HttpResponseForbidden
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View

import json

# Create your views here.
from django_redis import get_redis_connection

from apps.goods.models import SKU
from utils.response_code import RETCODE
from utils.cookiesecret import CookieSecret


class CartsView(View):

    # 查询
    def get(self, request):

        user = request.user
        if user.is_authenticated:
            carts_redis_client = get_redis_connection('carts')
            carts_data = carts_redis_client.hgetall(user.id)

            carts_dict = {}
            for data in carts_data.items():
                sku_key = int(data[0].decode())
                sku_data = json.loads(data[1].decode())

                carts_dict[sku_key] = sku_data

        else:
            cookie_str = request.COOKIES.get('carts')
            if cookie_str:
                carts_dict = CookieSecret.loads(cookie_str)
            else:
                carts_dict = {}

        skus = SKU.objects.filter(id__in = carts_dict.keys())

        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': carts_dict.get(sku.id).get('count'),
                'selected': str(carts_dict.get(sku.id).get('selected')),  # 将True，转'True'，方便json解析
                'default_image_url': sku.default_image.url,
                'price': str(sku.price),  # 从Decimal('10.2')中取出'10.2'，方便json解析
                'amount': str(sku.price * carts_dict.get(sku.id).get('count')),
            })


        context = {
            'cart_skus': cart_skus,
        }
        return render(request, 'cart.html', context)
    # 增加
    def post(self, request):
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        if not all([sku_id, count]):
            return HttpResponseForbidden('缺少必传参数')

        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return HttpResponseForbidden('商品不存在')

        try:
            count = int(count)
        except Exception as e:
            return HttpResponseForbidden('参数count有误')

        if selected:
            if not isinstance(selected, bool):
                return HttpResponseForbidden('参数selected有误')

        # 判断用户是否登录
        user = request.user

        if user.is_authenticated:
            # 用户已登录，操作redis购物车
            carts_redis_client = get_redis_connection('carts')
            client_data = carts_redis_client.hgetall(user.id)

            if not client_data:
                carts_redis_client.hset(user.id, sku_id, json.dumps({'count':count, 'selected':selected}))

            if str(sku_id).encode() in client_data:
                child_dict = json.loads(client_data[str(sku_id).encode()].decode())
                child_dict['count'] += count
                carts_redis_client.hset(user.id, sku_id, json.dumps(child_dict))

            else:
                carts_redis_client.hset(user.id, sku_id, json.dumps({'count':count, 'selected':selected}))

            return JsonResponse({'code': RETCODE.OK, 'errmsg': '添加购物车成功'})

        else:
            cookie_str = request.COOKIES.get('carts')
            if cookie_str:
                carts_dict = CookieSecret.loads(cookie_str)

            else:
                carts_dict = {}

            if sku_id in carts_dict:
                origin_count = carts_dict[sku_id]['count']
                count += origin_count

            carts_dict[sku_id] = {
                'count':count,
                'selected':selected,
            }

            cookie_cart_str = CookieSecret.dumps(carts_dict)

            # 创建响应对象
            response = JsonResponse({'code': RETCODE.OK, 'errmsg': '添加购物车成功'})
            # 响应结果并将购物车数据写入到cookie
            response.set_cookie('carts', cookie_cart_str, max_age=24 * 30 * 3600)
            return response
    # 修改
    def put(self, request):
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        if not all([sku_id, count]):
            return HttpResponseForbidden('缺少必传参数')

        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return HttpResponseForbidden('商品不存在')

        # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return HttpResponseForbidden('参数count有误')
        # 判断selected是否为bool值
        if selected:
            if not isinstance(selected, bool):
                return HttpResponseForbidden('参数selected有误')

        user = request.user
        cookie_cart_str = ""
        if user.is_authenticated:
            # 1.链接 redis
            carts_redis_client = get_redis_connection('carts')
            # 2.覆盖redis以前的数据
            new_data = {'count': count, 'selected': selected}
            carts_redis_client.hset(user.id, sku_id, json.dumps(new_data))

        else:
            cart_str = request.COOKIES.get('carts')

            if cart_str:
                cart_dict = CookieSecret.loads(cart_str)

            else:
                cart_dict = {}

            cart_dict[sku_id] = {
                'count':count,
                'selected':selected,
            }
            cookie_cart_str = CookieSecret.dumps(cart_dict)

        # 构建前端的数据
        cart_sku = {
            'id': sku_id,
            'count': count,
            'selected': selected,
            'name': sku.name,
            'default_image_url': sku.default_image.url,
            'price': sku.price,
            'amount': sku.price * count,
        }
        response = JsonResponse({'code': RETCODE.OK, 'errmsg': '修改购物车成功', 'cart_sku': cart_sku})
        if not user.is_authenticated:
            # 响应结果并将购物车数据写入到cookie
            response.set_cookie('carts', cookie_cart_str, max_age=24 * 30 * 3600)
        return response
    # 删除
    def delete(self, request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')

        # 判断sku_id是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return HttpResponseForbidden('商品不存在')

            # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 1.链接 redis
            carts_redis_client = get_redis_connection('carts')
            carts_redis_client.hdel(user.id, sku.id)

            # 删除结束后，没有响应的数据，只需要响应状态码即可
            return JsonResponse({'code': RETCODE.OK, 'errmsg': '删除购物车成功'})

        else:
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 转成明文
                cart_dict = CookieSecret.loads(cart_str)
            else:
                cart_dict = {}

            # 创建响应对象
            response = JsonResponse({'code': RETCODE.OK, 'errmsg': '删除购物车成功'})
            if sku_id in cart_dict:
                # 删除数据
                del cart_dict[sku_id]
                # 将字典转成密文
                cookie_cart_str = CookieSecret.dumps(cart_dict)
                # 响应结果并将购物车数据写入到cookie
                response.set_cookie('carts', cookie_cart_str, max_age=24 * 30 * 3600)
            return response